<template>
  <div class="app-container">
    <!-- 搜索条件区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="queryParams" ref="queryForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 200px"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="queryParams.roleCode" placeholder="请输入角色编码" clearable style="width: 200px"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 200px">
            <el-option label="正常" value="1"/>
            <el-option label="停用" value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="function-area">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:role:add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                     v-hasPermi="['system:role:edit']">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                     v-hasPermi="['system:role:remove']">删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:role:export']">
            导出
          </el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
          :data="roleList"
          @selection-change="handleSelectionChange"
        ref="table"
        @row-click="handleRowClick"
        fit
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="角色编号" prop="id" width="80"/>
        <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true"/>
        <el-table-column label="角色编码" prop="roleCode" :show-overflow-tooltip="true"/>
        <el-table-column label="角色描述" prop="description" :show-overflow-tooltip="true"/>
        <el-table-column label="排序" prop="sort" width="80"/>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
                v-hasPermi="['system:role:edit']"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template #default="scope">
            <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">修改
            </el-button>
            <el-button type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']">
              删除
            </el-button>
            <el-button type="text" icon="Key" @click="handleDataScope(scope.row)"
                       v-hasPermi="['system:role:permission']">数据权限
            </el-button>
            <el-button type="text" icon="Check" @click="handlePermissionScope(scope.row)"
                       v-hasPermi="['system:role:permission']">权限分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          v-show="total > 0"
          :total="total"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="form.roleName" placeholder="请输入角色名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色编码" prop="roleCode">
              <el-input v-model="form.roleCode" placeholder="请输入权限字符"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色顺序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input v-model="form.description" type="textarea" placeholder="请输入角色描述"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScope" width="600px" append-to-body>
      <el-form :model="form" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="form.roleCode" :disabled="true"/>
        </el-form-item>
        <el-form-item label="数据范围">
          <el-select v-model="form.dataScope" @change="handleDataScopeChange">
            <el-option label="全部数据权限" value="1"/>
            <el-option label="自定义数据权限" value="2"/>
            <el-option label="本部门数据权限" value="3"/>
            <el-option label="本部门及以下数据权限" value="4"/>
            <el-option label="仅本人数据权限" value="5"/>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope == '2'">
          <el-tree
              style="width: 500px"
              :data="deptOptions"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="deptTreeRef"
              :check-strictly="true"
              empty-text="加载中，请稍候"
              :props="{ label: 'name', children: 'children' }"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {listRole, getRole, delRole, addRole, updateRole, changeRoleStatus, dataScope} from "@/api/role";
import {treeselect as deptTreeselect, getCheckedDeptList} from "@/api/dept";
import {download} from "@/utils/download";

export default {
  name: "Role",
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示数据权限弹出层
      openDataScope: false,
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roleName: [
          {required: true, message: "角色名称不能为空", trigger: "blur"}
        ],
        roleCode: [
          {required: true, message: "角色权限字符不能为空", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "角色顺序不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      listRole(this.queryParams).then(response => {
        this.roleList = response.data.records;
        this.total = response.data.total;
      });
    },
    /** 查询部门树结构 */
    getDeptTree() {
      deptTreeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 所有部门节点数据
    getCheckedDepts(roleId) {
      getCheckedDeptList(roleId).then(response => {
        this.$refs.deptTreeRef.setCheckedKeys(response.data.checkedDeptIds);
      });
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return changeRoleStatus(row.id, row.status);
      }).then(() => {
        this.$message.success(text + "成功");
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消数据权限按钮
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.deptTreeRef) {
        this.$refs.deptTreeRef.setCheckedKeys([]);
      }
      this.form = {
        id: undefined,
        roleName: undefined,
        roleCode: undefined,
        sort: 0,
        status: 1,
        description: undefined,
        dataScope: '1',
        remark: undefined
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 处理行点击
    handleRowClick(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleId = row.id || this.ids[0];
      getRole(roleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改角色";
      });
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      this.getDeptTree();
      const roleId = row.id;
      getRole(roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.title = "分配数据权限";
        this.$nextTick(() => {
          this.getCheckedDepts(roleId);
        });
      });
    },
    /** 分配权限按钮操作 */
    handlePermissionScope(row) {
      const roleId = row.id;
      this.$router.push("/role-auth/" + roleId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateRole(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRole(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交数据权限按钮 */
    submitDataScope() {
      if (this.form.dataScope === '2') {
        this.form.deptIds = this.$refs.deptTreeRef.getCheckedKeys();
      } else {
        this.form.deptIds = [];
      }
      dataScope(this.form).then(response => {
        this.$message.success("修改成功");
        this.openDataScope = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delRole(roleIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      download('/api/system/role/export', this.ids, '角色数据.xlsx');
    },
    /** 数据权限变更时触发 */
    handleDataScopeChange(val) {
      if (val !== '2') {
        this.$refs.deptTreeRef.setCheckedKeys([]);
      }
    },
    /** 处理分页大小变化 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    /** 处理分页当前页变化 */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    }
  }
};
</script>
